//
//  GHY_CameraComponent.m
//  Camera
//
//  Created by aaaaaa on 16/8/10.
//  Copyright © 2016年 葛海一. All rights reserved.
//

#import "GHY_CameraComponent.h"
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
#import "GHY_CameraSetView.h"
#import "GHY_CameraAuxiliaryLineView.h"
#import <GLKit/GLKit.h>
#import <CoreImage/CoreImage.h>
#import "LAB_PhotoAlbumViewController.h"
#import "UIImage+GHY__Watermark.h"
#import "NSString+GHY_Width.h"

@interface GHY_CameraComponent ()<UIGestureRecognizerDelegate, AVCaptureVideoDataOutputSampleBufferDelegate, AVCaptureMetadataOutputObjectsDelegate>



// 捕获设备, 通常是前置摄像头, 后置摄像头, 麦克风(音频输入)
@property (nonatomic, retain) AVCaptureDevice *device;

// 输入设备, 使用AVCaptureDevice初始化
@property (nonatomic, retain) AVCaptureDeviceInput *input;

// 当启动摄像头开始捕获 用于获取实时图像
@property (nonatomic, retain) AVCaptureVideoDataOutput *output;

// 用于二维码识别以及人脸识别
@property (nonatomic, retain) AVCaptureMetadataOutput *metadataOutput;


// 输出流 用来捕捉静态图片
@property (nonatomic, retain) AVCaptureStillImageOutput *imageOutPut;

// 把输入和输出结合在一起, 并开始启动捕获设备(摄像头)
@property (nonatomic, retain) AVCaptureSession *session;

// 图像预览层, 实时显示捕获的图像
@property (nonatomic, retain) AVCaptureVideoPreviewLayer *previewLayer;

// 上面设置的视图
@property (nonatomic, retain) BaseView *topSetUpView;

// 返回按钮
@property (nonatomic, retain) BaseButton *backBtn;

// 设置按钮
@property (nonatomic, retain) BaseButton *setBtn;


// 转换摄像头按钮
@property (nonatomic, retain) BaseButton *convertCameraBtn;


// 设置栏
@property (nonatomic, retain) BaseView *setView;

// 闪光灯
@property (nonatomic, retain) GHY_CameraSetView *flashView;

// 辅助线
@property (nonatomic, retain) GHY_CameraSetView *auxiliaryLineView;

// 延时
@property (nonatomic, retain) GHY_CameraSetView *timeDelayView;

// 水印
@property (nonatomic, retain) GHY_CameraSetView *watermarkView;

// 水印视图
@property (nonatomic, retain) UILabel *watermarkLable;



// 辅助线视图
@property (nonatomic, retain) GHY_CameraAuxiliaryLineView *auxiliaryView;




// 下面的视图
@property (nonatomic, retain) BaseView *bottomPhotoView;


// 拍照按钮
@property (nonatomic, retain) BaseButton *photoBtn;

// 照片
@property (nonatomic, retain) UIImage *image;

// 显示照片
@property (nonatomic, retain) UIImageView *imageView;

// 相册button
@property (nonatomic, retain) BaseButton *photoAlbumBtn;

// 换滤镜btn
@property (nonatomic, retain) BaseButton *filterBtn;






// 聚焦视图
@property (nonatomic, retain) BaseView *focusView;





// 记录开始的缩放比例
@property (nonatomic, assign) CGFloat beginGestureScale;

// 最后的缩放比例
@property (nonatomic, assign) CGFloat effectiveScale;


@property (nonatomic, retain) GLKView *videoPreviewView;
@property (nonatomic, retain) CIContext *ciContext;
@property (nonatomic, retain) EAGLContext *eaglContext;


// 滤镜数组
@property (nonatomic, retain) NSArray<NSString *> *filterArr;

@property (nonatomic, assign) NSInteger filterIndex;



@property (nonatomic, retain) NSMutableArray<UILabel *> *facelableArr;




@end

@implementation GHY_CameraComponent

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        if ([self canUserCamear] && [self canUserPhotoAlbum]) {
            self.effectiveScale = self.beginGestureScale = 1.0;
            [self createGLKView];
            [self customCamera];
            [self createAuxiliaryView];
            [self createTopSetUpView];
            [self createBottomPhotoView];
            [self createOtherSubViews];
            [self createSetView];
            [self addTap];
            [self createBlock];
        }
        
        
    }
    return self;
}



- (void)createGLKView{
    self.filterIndex = 0;
    self.filterArr = [NSArray arrayWithObjects:
                      @"CIColorCrossPolynomial",
                      @"CIColorCube",
                      @"CIColorCubeWithColorSpace",
                      @"CIColorInvert",
                      @"CIColorMonochrome",
                      @"CIColorPosterize",
                      @"CIFalseColor",
                      @"CIMaskToAlpha",
                      @"CIMaximumComponent",
                      @"CIMinimumComponent",
                      @"CIPhotoEffectChrome",
                      @"CIPhotoEffectFade",
                      @"CIPhotoEffectInstant",
                      @"CIPhotoEffectMono",
                      @"CIPhotoEffectNoir",
                      @"CIPhotoEffectProcess",
                      @"CIPhotoEffectTonal",
                      @"CIPhotoEffectTransfer",
                      @"CISepiaTone",
                      @"CIVignette", nil];
    
    self.eaglContext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
    self.videoPreviewView = [[GLKView alloc] initWithFrame:CGRectMake(0, HEIGHT * 0.1, WIDTH, HEIGHT * 0.75) context:self.eaglContext];
    [self addSubview:_videoPreviewView];
     _ciContext = [CIContext contextWithEAGLContext:_eaglContext options:@{kCIContextWorkingColorSpace : [NSNull null]} ];
    
    
    
    
}

// 检查相机权限
- (BOOL)canUserCamear {
    
    BOOL flag;
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusDenied) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请求打开相机权限" message:@"设置-隐私-相机" preferredStyle:UIAlertControllerStyleAlert];
        
        __block BOOL flagcopy = flag;
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            flagcopy = NO;
        }];
        
        UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            
            if ([[UIApplication sharedApplication] canOpenURL:url]) {
                [[UIApplication sharedApplication] openURL:url];
                flagcopy = YES;
            }
        }];
        
        [alert addAction:confirmAction];
        [alert addAction:cancelAction];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.controller presentViewController:alert animated:YES completion:^{
            }];
        });
        
        return flag;
    } else {
        return YES;
    }

    
    
}

// 获取相册权限
- (BOOL)canUserPhotoAlbum{
    BOOL flag;
    PHAuthorizationStatus authStatus = [PHPhotoLibrary authorizationStatus];
    if (authStatus != PHAuthorizationStatusAuthorized) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请求打开相册权限" message:@"设置-隐私-相机" preferredStyle:UIAlertControllerStyleAlert];
        
        __block BOOL flagcopy = flag;
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            flagcopy = NO;
        }];
        
        UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            
            if ([[UIApplication sharedApplication] canOpenURL:url]) {
                [[UIApplication sharedApplication] openURL:url];
                flagcopy = YES;
            }
        }];
        
        [alert addAction:confirmAction];
        [alert addAction:cancelAction];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.controller presentViewController:alert animated:YES completion:^{
            }];
        });
        
        return flag;

    } else {
        return YES;
    }
}


// 获取最后一次的照片
- (UIImage *)lastPhotoLibrary{
    
    // 列出所有相册智能相册
//    PHFetchResult *result = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    
    // 列出所有用户创建的相册
//    PHFetchResult *userResult = [PHCollectionList fetchTopLevelUserCollectionsWithOptions:nil];
    
    // 获取所有资源的集合, 并按资源的创建时间排序
    PHFetchOptions *optiond = [[PHFetchOptions alloc] init];
    optiond.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
    PHFetchResult *allresult = [PHAsset fetchAssetsWithOptions:optiond];
    
    PHCachingImageManager *imageManager = [[PHCachingImageManager alloc] init];
    PHAsset *asset = allresult.lastObject;
    
    UIImage *image = [[UIImage alloc] init];
    
    __block UIImage *imageCopy = image;
    [imageManager requestImageForAsset:asset targetSize:CGSizeMake(WIDTH, WIDTH) contentMode:PHImageContentModeAspectFill options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        imageCopy = result;
    }];
    
    
    return imageCopy;
}

// 实时滤镜
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection{
    
   
   
    
//    [connection setVideoOrientation:AVCaptureVideoOrientationPortrait];
    
    
    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    CIImage *sourceImage = [CIImage imageWithCVImageBuffer:imageBuffer options:nil];
    CGRect sourceExtent = sourceImage.extent;
    
    CIFilter *effectFilter = [CIFilter filterWithName:self.filterArr[self.filterIndex]];
    [effectFilter setValue:sourceImage forKey:kCIInputImageKey];
    sourceImage = [effectFilter outputImage];
    
   
    
    CGFloat sourceAspect = sourceExtent.size.width / sourceExtent.size.height;
    CGFloat previewAspect = self.videoPreviewView.bounds.size.width  / self.videoPreviewView.bounds.size.height;
    
    // we want to maintain the aspect radio of the screen size, so we clip the video image
    CGRect drawRect = sourceExtent;
    if (sourceAspect > previewAspect)
    {
        // use full height of the video image, and center crop the width
        drawRect.origin.x += (drawRect.size.width - drawRect.size.height * previewAspect) / 2.0;
        drawRect.size.width = drawRect.size.height * previewAspect;
    }
    else
    {
        // use full width of the video image, and center crop the height
        drawRect.origin.y += (drawRect.size.height - drawRect.size.width / previewAspect) / 2.0;
        drawRect.size.height = drawRect.size.width / previewAspect;
    }
    
    [_videoPreviewView bindDrawable];
    
    if (_eaglContext != [EAGLContext currentContext])
        [EAGLContext setCurrentContext:_eaglContext];
    
    // clear eagl view to grey
    glClearColor(0.5, 0.5, 0.5, 1.0);
    glClear(GL_COLOR_BUFFER_BIT);
    
    // set the blend mode to "source over" so that CI will use that
    glEnable(GL_BLEND);
    glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
    

    
    if (sourceImage)
        [_ciContext drawImage:sourceImage inRect:CGRectMake(0, 0, self.videoPreviewView.drawableWidth, self.videoPreviewView.drawableHeight) fromRect:drawRect];
    
    [_videoPreviewView display];
    
    
}

// AVCaptureMetadataOutputObjectsDelegate 人脸识别
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    
    if (metadataObjects.count > 0) {
        
        
        for (int i = 0; i < metadataObjects.count; i++) {
            AVMetadataMachineReadableCodeObject *metadataObject = [metadataObjects objectAtIndex:i];
            AVMetadataObject *faceData = [self.previewLayer transformedMetadataObjectForMetadataObject:metadataObject];
            
            if (i == self.facelableArr.count) {
                UILabel *faceLable = [[UILabel  alloc] init];
                faceLable.layer.borderWidth = 1;
                faceLable.layer.borderColor = [UIColor whiteColor].CGColor;
                [self.videoPreviewView addSubview:faceLable];
                faceLable.hidden = YES;
                [self.facelableArr addObject:faceLable];
            }
            
            self.facelableArr[i].hidden = NO;
            
            AVCaptureDevicePosition posotion = [[_input device] position];
            if (posotion == AVCaptureDevicePositionFront) {
                self.facelableArr[i].frame = CGRectMake(faceData.bounds.origin.x , HEIGHT * 0.9 - faceData.bounds.size.height - faceData.bounds.origin.y, faceData.bounds.size.width, faceData.bounds.size.height);
                
            } else {
                self.facelableArr[i].frame = faceData.bounds;
            }
            
        }
        
    }

    
    
    if (metadataObjects.count < self.facelableArr.count) {
        
        for (int i = metadataObjects.count; i < self.facelableArr.count; i++) {
            self.facelableArr[i].hidden = YES;
        }
        
    }
    
   
}

- (void)customCamera{
    
    self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    self.input = [[AVCaptureDeviceInput alloc] initWithDevice:self.device error:nil];
    
    // 生成输出对象
//    self.output = [[AVCaptureMetadataOutput alloc] init];
    self.output = [[AVCaptureVideoDataOutput alloc] init];
    NSDictionary *outputSettings = @{ (id)kCVPixelBufferPixelFormatTypeKey : [NSNumber numberWithInteger:kCVPixelFormatType_32BGRA]};
    // create and configure video data output

    self.output.videoSettings = outputSettings;
    [self.output setSampleBufferDelegate:self queue:dispatch_queue_create("capture_session_queue", NULL)];
    self.output.alwaysDiscardsLateVideoFrames = YES;
    
    self.imageOutPut = [[AVCaptureStillImageOutput alloc] init];
    
    // 结合输入输出
    self.session = [[AVCaptureSession alloc] init];
    
    if ([self.session canSetSessionPreset:AVCaptureSessionPreset1280x720]) {
        self.session.sessionPreset = AVCaptureSessionPreset1280x720;
    }
    
    if ([self.session canAddInput:self.input]) {
        
        [self.session addInput:self.input];
    }
    
    
    if ([self.session canAddOutput:self.imageOutPut]) {
        
        [self.session addOutput:self.imageOutPut];
    }
    if ([self.session canAddOutput:self.output]) {
        
        [self.session addOutput:self.output];
    }
    
    self.metadataOutput = [[AVCaptureMetadataOutput alloc] init];
    [self.metadataOutput setMetadataObjectsDelegate:self  queue:dispatch_get_main_queue()];
    
    // 设置扫描区域
    self.metadataOutput.rectOfInterest = self.bounds;
    
    
    if ([self.session canAddOutput:self.metadataOutput]) {
        [self.session addOutput:self.metadataOutput];
    }
    // 设置人脸识别
    self.metadataOutput.metadataObjectTypes = @[AVMetadataObjectTypeFace];
    
    
    

    self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    self.previewLayer.bounds = CGRectMake(0, 0, WIDTH, HEIGHT * 0.9);
    self.previewLayer.position = CGPointMake(WIDTH / 2, HEIGHT / 2);
    self.previewLayer.frame = CGRectMake(0, 0, WIDTH, HEIGHT * 0.9);
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;

//    [self.videoPreviewView.layer addSublayer:self.previewLayer];
    [self.session startRunning];
    
    [self.output.connections[0] setVideoOrientation:AVCaptureVideoOrientationPortrait];
}

// 上面设置栏
- (void)createTopSetUpView{
    
    self.topSetUpView = [[BaseView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT * 0.1)];
    [self addSubview:_topSetUpView];
    self.topSetUpView.backgroundColor = [UIColor whiteColor];
    
    self.convertCameraBtn = [BaseButton buttonWithType:UIButtonTypeCustom];
    [self.convertCameraBtn setImage:[UIImage imageNamed:@"conversion_btn"] forState:UIControlStateNormal];
    
    [self.topSetUpView addSubview:self.convertCameraBtn];
    
    [self.convertCameraBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.topSetUpView.mas_right);
        make.centerY.equalTo(self.topSetUpView.mas_centerY).offset(10);
        make.height.mas_offset((HEIGHT * 0.1 - 20) * 0.8);
        make.width.mas_offset((HEIGHT * 0.1 - 20) * 0.8);
    }];
    
    [self.convertCameraBtn addTarget:self action:@selector(convertCameraAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.setBtn = [BaseButton buttonWithType:UIButtonTypeCustom];
//    [self.setBtn setTitle:@"aa" forState:UIControlStateNormal];
    [self.setBtn setImage:[UIImage imageNamed:@"set_btn"] forState:UIControlStateNormal];
//    [self.setBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    
    [self.topSetUpView addSubview:_setBtn];
    
    [self.setBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
       
        make.centerX.equalTo(self.topSetUpView.mas_centerX);
        make.centerY.equalTo(self.convertCameraBtn.mas_centerY);
        make.height.equalTo(self.convertCameraBtn);
        make.width.equalTo(self.convertCameraBtn);
        
    }];
    
    [self.setBtn addTarget:self action:@selector(setBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.backBtn = [BaseButton buttonWithType:UIButtonTypeCustom];
    [self.backBtn setImage:[UIImage imageNamed:@"BackBtn"] forState:UIControlStateNormal];
    [self.topSetUpView addSubview:_backBtn];
    
    [self.backBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
       
        make.left.equalTo(self.topSetUpView.mas_left);
        make.centerY.equalTo(self.topSetUpView.mas_centerY).offset(10);
        make.height.mas_offset((HEIGHT * 0.1 - 20) * 0.8);
        make.width.mas_offset((HEIGHT * 0.1 - 20) * 0.8);
        
    }];
    
    [self.backBtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)backAction:(UIButton *)btn{
    
    [self.controller.navigationController popViewControllerAnimated:YES];
    
}

- (void)setBtnAction:(UIButton *)btn
{
    self.setView.hidden = self.setBtn.selected;
    
    self.setBtn.selected =! self.setBtn.selected;
}

// 设置栏
- (void)createSetView{
    
    self.setView = [[BaseView alloc] initWithFrame:CGRectMake(0, HEIGHT * 0.1, WIDTH, HEIGHT * 0.13)];
    
    self.setView.backgroundColor = [UIColor colorWithRed:0.10f green:0.10f blue:0.10f alpha:0.5f];
    
    NSMutableArray<GHY_CameraSetView *> *viewArr = [NSMutableArray array];
    for (int i = 0; i < 4; i++) {
        GHY_CameraSetView *setView = [[GHY_CameraSetView alloc] initWithFrame:CGRectMake(i * WIDTH_VIEW / 4, 0, WIDTH_VIEW / 4, HEIGHT * 0.13)];
        [self.setView addSubview:setView];
        [viewArr addObject:setView];
    }
    
    self.flashView = viewArr[0];
    self.auxiliaryLineView = viewArr[1];
    self.timeDelayView = viewArr[2];
    self.watermarkView = viewArr[3];
    
//    self.flashView.textColor = [UIColor orangeColor];
    
    [self addSubview:_setView];
    
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    if ([user boolForKey:@"first"]) {
        self.flashView.status = [user integerForKey:@"flashView"];
        self.auxiliaryLineView.status = [user integerForKey:@"auxiliaryLineView"];
        self.timeDelayView.status = [user integerForKey:@"timeDelayView"];
    }
    
    
    
    [self changeAusiliary];
    [self changeTimeDelay];
    [self changeFlash];
    [self changeWater];
    
    
    UITapGestureRecognizer *flashTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(flashAction:)];
    [self.flashView addGestureRecognizer:flashTap];
    
    UITapGestureRecognizer *auxiliaryLineTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(auxiliaryAction:)];
    [self.auxiliaryLineView addGestureRecognizer:auxiliaryLineTap];
    
    UITapGestureRecognizer *timeDelayTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(timeDelayAction:)];
    [self.timeDelayView addGestureRecognizer:timeDelayTap];
    
    
    UITapGestureRecognizer *watermarkTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(watermarkAction:)];
    [self.watermarkView addGestureRecognizer:watermarkTap];
    
    self.setView.hidden = YES;  
    
}

- (void)createBlock{
    
    __weak GHY_CameraComponent *camera = self;
    
    self.viewWillDisAppear = ^(void) {
        
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        [user setBool:YES forKey:@"first"];
        [user setInteger:camera.flashView.status forKey:@"flashView"];
        [user setInteger:camera.auxiliaryLineView.status forKey:@"auxiliaryLineView"];
        [user setInteger:camera.timeDelayView.status forKey:@"timeDelayView"];

        
    };
}

// 设置闪光灯状态
- (void)flashAction:(UITapGestureRecognizer *)tap{
    
    self.flashView.status ++;
    self.flashView.status %= 3;

    [self changeFlash];
}

- (void)changeFlash{
    [self.device lockForConfiguration:nil];
    if ([self.device hasFlash]) {
        
        switch (self.flashView.status) {
            case 0:
            {
                self.device.flashMode = AVCaptureFlashModeAuto;
                self.flashView.imageStr = @"flash_auto";
                self.flashView.titleStr = @"闪光自动";
                self.flashView.textColor = [UIColor orangeColor];
            }
                break;
            case 1:
            {
                self.device.flashMode = AVCaptureFlashModeOn;
                self.flashView.imageStr = @"flash_on";
                self.flashView.titleStr = @"闪光打开";
                self.flashView.textColor = [UIColor orangeColor];
            }
                break;
            case 2:
            {
                self.device.flashMode = AVCaptureFlashModeOff;
                self.flashView.imageStr = @"flash_off";
                self.flashView.titleStr = @"闪光关闭";
                self.flashView.textColor = [UIColor whiteColor];
            }
                break;
            default:
                break;
        }
    }
}



// 辅助线View
- (void)createAuxiliaryView{
     self.auxiliaryView = [[GHY_CameraAuxiliaryLineView alloc] initWithFrame:self.videoPreviewView.frame];
    [self addSubview:self.auxiliaryView];
    self.auxiliaryView.hidden = YES;
}

// 设置辅助线
- (void)auxiliaryAction:(UITapGestureRecognizer *)tap{
 
    self.auxiliaryLineView.status = !self.auxiliaryLineView.status;
    [self changeAusiliary];
}

- (void)changeAusiliary{
    
    self.auxiliaryLineView.titleStr = @"辅助线";
    
    if (!self.auxiliaryLineView.status) {
        self.auxiliaryLineView.imageStr = @"auxiliaryline_off";
        self.auxiliaryLineView.textColor = [UIColor whiteColor];
        self.auxiliaryView.hidden = YES;
    } else {
        
        self.auxiliaryLineView.imageStr = @"auxiliaryline_on";
        self.auxiliaryLineView.textColor = [UIColor orangeColor];
        self.auxiliaryView.hidden = NO;
    }
}

// 延时拍摄
- (void)timeDelayAction:(UITapGestureRecognizer *)tap{
    
    self.timeDelayView.status++;
    self.timeDelayView.status %= 3;
    [self changeTimeDelay];
}

- (void)changeTimeDelay{
    switch (self.timeDelayView.status) {
        case 0:
        {
            self.timeDelayView.imageStr = @"timeDelay_off";
            self.timeDelayView.titleStr = @"延时关闭";
            self.timeDelayView.textColor = [UIColor whiteColor];
        }
            break;
        case 1:
        {
            self.timeDelayView.imageStr = @"timeDelay_on";
            self.timeDelayView.titleStr = @"延时3秒";
            self.timeDelayView.textColor = [UIColor orangeColor];
        }
            break;
        case 2:
        {
            self.timeDelayView.imageStr = @"timeDelay_on";
            self.timeDelayView.titleStr = @"延时5秒";
            self.timeDelayView.textColor = [UIColor orangeColor];
        }
            break;
        default:
            break;
    }
}

// 延时动画
- (void)timeDelayAnimation:(NSInteger)time withLalbe:(UILabel *)lable{
    lable.text = [NSString stringWithFormat:@"%ld", (long)time];
    __block NSInteger newtime = time;
    [UIView animateWithDuration:1 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        lable.transform = CGAffineTransformScale(lable.transform, 3, 3);
    } completion:^(BOOL finished) {
        newtime--;
        if (newtime == 0) {
            [lable removeFromSuperview];
            return ;
        }
        lable.transform = CGAffineTransformScale(lable.transform, 1 / 3.0, 1 / 3.0);
        [self timeDelayAnimation:newtime withLalbe:lable];
        
    }];
    
    
}

// 显示水印
- (void)watermarkAction:(UITapGestureRecognizer *)tap{
    
    self.watermarkView.status = !self.watermarkView.status;
    [self changeWater];
    
}

- (void)changeWater{
    
    if (self.watermarkView.status) {
        
        self.watermarkView.imageStr = @"watermark_on";
        self.watermarkView.textColor = [UIColor orangeColor];
        self.watermarkView.titleStr = @"水印开启";
        
        self.watermarkLable = [[UILabel alloc]  init];
        [self addSubview:_watermarkLable];
        self.watermarkLable.textAlignment = NSTextAlignmentRight;
        self.watermarkLable.textColor = [UIColor whiteColor];
        
        [self.watermarkLable mas_remakeConstraints:^(MASConstraintMaker *make) {
            
            make.left.equalTo(self.mas_left);
            make.right.equalTo(self.mas_right);
            make.bottom.equalTo(self.bottomPhotoView.mas_top);
            make.height.mas_offset(HEIGHT * 0.05);
            
        }];
        //        self.watermarkLable.backgroundColor = [UIColor orangeColor];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请输入水印文字" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            
            textField.placeholder = @"请输入水印文字";
            
        }];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            self.watermarkLable.text = alert.textFields[0].text;
        }];
        
        [alert addAction:action];
        
        [self.controller presentViewController:alert animated:YES completion:^{
            
        }];
        
        
    } else {
        self.watermarkView.imageStr = @"watermark_off";
        self.watermarkView.textColor = [UIColor whiteColor];
        self.watermarkView.titleStr = @"水印关闭";
        
        [self.watermarkLable removeFromSuperview];
        
    }
}

// 转换前后摄像头
- (void)convertCameraAction:(UIButton *)btn{
    
    NSInteger cameraCount = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];
    if (cameraCount > 1) {
        
        CATransition *animation = [CATransition animation];
        animation.duration = 0.5f;
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
        animation.type = @"oglFlip";
        
        AVCaptureDevice *newCamera = nil;
        AVCaptureDeviceInput *newInput = nil;
        
        // 获取另一个摄像头的位置
        AVCaptureDevicePosition posotion = [[_input device] position];
        if (posotion == AVCaptureDevicePositionFront) {
            newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
        } else {
            newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
        }
        animation.subtype = kCATransitionFromRight;
        
       
        
        newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:nil];
        [self.videoPreviewView.layer addAnimation:animation forKey:nil];
        
        [self.session stopRunning];
        
        for (int i = 0; i < self.facelableArr.count; i++) {
            self.facelableArr[i].hidden = YES;
        }
        
        [self.session beginConfiguration];
        [self.session removeInput:_input];
        
        if ([self.session canAddInput:newInput]) {
            [self.session addInput:newInput];
            self.input = newInput;
        } else {
            [self.session addInput:self.input];
        }
        
        [self.session commitConfiguration];
        [self.session startRunning];
        
        AVCaptureDevicePosition position = [[self.input device] position];
        if (position == AVCaptureDevicePositionFront){
            // 取消前置镜像!!!!
            self.videoPreviewView.transform =  CGAffineTransformMake(1, 0, 0, -1, 0, 0);
            
            // 更改方向
            [self.output.connections[0] setVideoOrientation:AVCaptureVideoOrientationPortraitUpsideDown];
            
        }else {
            self.videoPreviewView.transform =CGAffineTransformRotate(CGAffineTransformIdentity, 0);
            // 更改方向
            
            [self.output.connections[0] setVideoOrientation:AVCaptureVideoOrientationPortrait];
        }
        
    }
    
}

// 根据摄像头位置获取摄像头
- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position{
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *device in devices) {
        if (device.position == position) {
            return device;
        }
    }
    
    return nil;
}


// 下面设置栏
- (void)createBottomPhotoView{
    
    self.bottomPhotoView = [[BaseView alloc] initWithFrame:CGRectMake(0, HEIGHT * 0.85, WIDTH, HEIGHT * 0.15)];
    [self addSubview:_bottomPhotoView];
     self.bottomPhotoView.backgroundColor = [UIColor whiteColor];
    
    self.photoBtn = [BaseButton buttonWithType:UIButtonTypeCustom];
    [self.photoBtn setImage:[[UIImage imageNamed:@"icon_camera"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]forState:UIControlStateNormal];
    [self.bottomPhotoView addSubview:_photoBtn];
    
    self.photoBtn.backgroundColor = [UIColor colorWithRed:0.10f green:0.10f blue:0.10f alpha:1.0f];
//    self.photoBtn.layer.borderColor = [UIColor whiteColor].CGColor;
//    self.photoBtn.layer.borderWidth = 1.0;
    self.photoBtn.layer.cornerRadius = HEIGHT * 0.15 * 0.4;
    self.photoBtn.layer.masksToBounds = YES;
    
    [_photoBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
       
        make.centerY.equalTo(self.bottomPhotoView.mas_centerY);
        make.centerX.equalTo(self.bottomPhotoView.mas_centerX);
        make.height.mas_equalTo(HEIGHT * 0.15 * 0.8);
        make.width.mas_equalTo(HEIGHT * 0.15 * 0.8);
        
    }];
    
    [self.photoBtn addTarget:self action:@selector(photoAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.photoAlbumBtn = [BaseButton buttonWithType:UIButtonTypeCustom];
//    [self.photoAlbumBtn setImage:[self firstPhotoLibrary] forState:UIControlStateNormal];
    [self.photoAlbumBtn setBackgroundImage:[self lastPhotoLibrary] forState:UIControlStateNormal];
    [self addSubview:_photoAlbumBtn];
    
    [self.photoAlbumBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
       
        make.centerY.equalTo(self.photoBtn.mas_centerY);
        make.height.mas_equalTo(HEIGHT * 0.15 * 0.8 * 0.8);
        make.width.mas_equalTo(HEIGHT * 0.15 * 0.8 * 0.8);
        make.left.equalTo(self.bottomPhotoView.mas_left).offset(WIDTH * 0.1);
        
    }];
    self.photoAlbumBtn.layer.cornerRadius = 3;
    self.photoAlbumBtn.layer.masksToBounds = YES;
    [self.photoAlbumBtn addTarget:self action:@selector(jumpPhotoAlbrm:) forControlEvents:UIControlEventTouchUpInside];
    
    self.filterBtn = [BaseButton buttonWithType:UIButtonTypeCustom];
    [self.bottomPhotoView addSubview:_filterBtn];
    
//    [self.filterBtn setTitle:@"换" forState:UIControlStateNormal];
//    [self.filterBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [self.filterBtn setImage:[UIImage imageNamed:@"random_btn"] forState:UIControlStateNormal];
    [self.filterBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
       
        make.centerY.equalTo(self.photoBtn);
        make.height.equalTo(self.photoAlbumBtn);
        make.width.equalTo(self.photoAlbumBtn);
        make.right.equalTo(self.bottomPhotoView.mas_right).offset(- WIDTH * 0.1);
        
    }];
    
    [self.filterBtn addTarget:self action:@selector(filterChangeAction) forControlEvents:UIControlEventTouchUpInside];
    
}


// 拍照
- (void)photoAction:(UIButton *)btn{
    
    AVCaptureConnection *videoConnection = [self.imageOutPut connectionWithMediaType:AVMediaTypeVideo];
    [videoConnection setVideoScaleAndCropFactor:self.effectiveScale];
    if (!videoConnection) {
        NSLog(@"拍照失败!");
        return;
    }
    
    
    UILabel *lable = [[UILabel alloc] init];
    [self addSubview:lable];
    lable.textColor = [UIColor orangeColor];
    lable.textAlignment = NSTextAlignmentCenter;
    lable.font = [UIFont systemFontOfSize:30];
    [lable mas_remakeConstraints:^(MASConstraintMaker *make) {
       
        make.centerX.equalTo(self.mas_centerX);
        make.centerY.equalTo(self.mas_centerY);
        make.height.mas_offset(30);
        make.width.mas_offset(30);
        
    }];
    int time;
    switch (self.timeDelayView.status) {
        case 0:
        {
            time = 0;
        }
            break;
        case 1:
        {
            time = 3;
            [self timeDelayAnimation:3 withLalbe:lable];
        }
            break;
        case 2:
        {
            time = 5;
            [self timeDelayAnimation:5 withLalbe:lable];
        }
            break;
        default:
            break;
    }
    
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.imageOutPut captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
            
            if (imageDataSampleBuffer == NULL) {
                return ;
            }
            
            
            NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
            UIImage *image = [UIImage imageWithData:imageData];
            [self.session stopRunning];
            
            self.image = image;
            self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, HEIGHT * 0.1, WIDTH, HEIGHT * 0.75)];
            
            if(self.watermarkView.status){
                [self insertSubview:_imageView aboveSubview:_watermarkLable];
            } else {
                [self insertSubview:_imageView belowSubview:_bottomPhotoView];
                
            }
            
            self.imageView.layer.masksToBounds = YES;
            
            //转换Image格式
            CIImage * ciImg = [[CIImage alloc] initWithImage:image];
            //创建
            CIFilter * filter = [CIFilter filterWithName:self.filterArr[self.filterIndex] keysAndValues:kCIInputImageKey,ciImg, nil];
            [filter setDefaults];
            //绘制内容
            CIContext * context = [CIContext contextWithOptions:nil];
            //渲染输出
            CIImage * outFilterImg = [filter outputImage];
            //CGImage句柄
            CGImageRef cgImg = [context createCGImage:outFilterImg fromRect:[outFilterImg extent]];
            
            
            // 翻转图片
            self.image = [UIImage imageWithCGImage:cgImg scale:1.0 orientation:UIImageOrientationRight];


            // 取消前置摄像头的镜像
            AVCaptureDevicePosition posotion = [[_input device] position];
            if (posotion == AVCaptureDevicePositionFront){
                self.image = [UIImage imageWithCGImage:self.image.CGImage scale:1 orientation:UIImageOrientationLeftMirrored];
            }
            
            // 图片加水印
            if (self.watermarkView.status) {
                
                
                self.image = [self.image addText:self.image text:self.watermarkLable.text withRect:CGRectMake(0, self.image.size.height - HEIGHT * 0.05, WIDTH, HEIGHT * 0.05)];
            }
            
            self.imageView.image = _image;
            [self saveImageToPhotoAlbum:self.image];
            
            
        }];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            
            [self.photoAlbumBtn setBackgroundImage:_image forState:UIControlStateNormal];
            [self.imageView removeFromSuperview];
            [self.session startRunning];
        });
    
    });
    
    
    
}


// 跳转到相册
- (void)jumpPhotoAlbrm:(UIButton *)btn{
 
    LAB_PhotoAlbumViewController *albumVc = [[LAB_PhotoAlbumViewController alloc] init];
    [self.controller.navigationController pushViewController:albumVc animated:YES];
    
}

// 更换滤镜
- (void)filterChangeAction{
    self.filterIndex++;
    if (self.filterIndex == self.filterArr.count) {
        self.filterIndex = 0;
    }
}


// 除了上面和下面的视图
- (void)createOtherSubViews{
    
    self.focusView = [[BaseView alloc] initWithFrame:CGRectMake(0, 0, HEIGHT * 0.15, HEIGHT * 0.15)];
    self.focusView.layer.borderWidth = 1.0;
    self.focusView.layer.borderColor = [UIColor whiteColor].CGColor;
    self.focusView.backgroundColor = [UIColor clearColor];
    [self addSubview:_focusView];
    self.focusView.hidden = YES;
    
    self.facelableArr = [NSMutableArray array];
    for (int i = 0; i < 2;  i ++) {
        
        UILabel *faceLable = [[UILabel  alloc] init];
        faceLable.layer.borderWidth = 1;
        faceLable.layer.borderColor = [UIColor whiteColor].CGColor;
        [self.videoPreviewView addSubview:faceLable];
        faceLable.hidden = YES;
        [self.facelableArr addObject:faceLable];
    }
    
   
    
}

// 保存图片
- (void)saveImageToPhotoAlbum:(UIImage *)savedImage{
    UIImageWriteToSavedPhotosAlbum(savedImage, self, nil, NULL);
}



// 添加手势
- (void)addTap{
    
    // 聚焦
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(focusGesture:)];
    [self addGestureRecognizer:tapGesture];
    
    // 放大缩小
    UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handelPinchFesture:)];
    pinchGesture.delegate = self;
    [self addGestureRecognizer:pinchGesture];
    
    //更换滤镜
    UISwipeGestureRecognizer *swipGestureRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipChangeFilter:)];
    swipGestureRight.direction = UISwipeGestureRecognizerDirectionRight;
    [self addGestureRecognizer:swipGestureRight];
    
    UISwipeGestureRecognizer *swipGestureLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(filterChangeAction)];
    swipGestureLeft.direction = UISwipeGestureRecognizerDirectionLeft;
    [self addGestureRecognizer:swipGestureLeft];
    
}

// 聚焦
- (void)focusGesture:(UITapGestureRecognizer *)gesture {
    
    if (self.setView.hidden == NO) {
        self.setBtn.selected = !self.setBtn.selected;
        self.setView.hidden = YES;
        return;
    }
    
    CGPoint point = [gesture locationInView:gesture.view];
    CGPoint focusPoint = CGPointMake(point.y / WIDTH, 1 - point.x / HEIGHT);
    
    NSError *error;
    
    if ([self.device lockForConfiguration:&error]) {
        // 对焦模式和对焦点
        if ([self.device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
            [self.device setFocusPointOfInterest:focusPoint];
            [self.device setFocusMode:AVCaptureFocusModeAutoFocus];
        }
        
        // 曝光模式和曝光点
        if ([self.device isExposureModeSupported:AVCaptureExposureModeAutoExpose]) {
            [self.device setExposurePointOfInterest:focusPoint];
            [self.device setExposureMode:AVCaptureExposureModeAutoExpose];
        }
        
        [self.device unlockForConfiguration];
        self.focusView.center = point;
        self.focusView.hidden = NO;
        // 设置对焦动画
        [UIView animateWithDuration:0.3 animations:^{
            _focusView.transform = CGAffineTransformMakeScale(1.25, 1.25);
        } completion:^(BOOL finished) {
            
            [UIView animateWithDuration:0.5 animations:^{
                self.focusView.transform = CGAffineTransformIdentity;
            } completion:^(BOOL finished) {
                _focusView.hidden = YES;
                
            }];
            
        }];
        
    }
    
    
    // 自动聚焦(手动聚焦之后自动聚焦会失效)
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        NSError *err = nil;
        if ([self.device lockForConfiguration:&err]) {
            if ([_device isFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus]) {
                
                [_device setFocusMode:AVCaptureFocusModeContinuousAutoFocus];
            }
            
        }
        [self.device unlockForConfiguration];
        
    });
    
    
    
}


// 手势缩小和放大
- (void)handelPinchFesture:(UIPinchGestureRecognizer *)pinch{
    
//    NSInteger numTouchs = [pinch numberOfTouches];
//    for (int i = 0; i < numTouchs; i++) {
//        CGPoint location = [pinch locationOfTouch:i inView:self];
//        CGPoint convertrdLocation = [self.previewLayer convertPoint:location toLayer:self.previewLayer];
//        if (![self.previewLayer containsPoint:convertrdLocation]) {
//            return;
//        }
//    }
    
    self.effectiveScale = self.beginGestureScale * pinch.scale;
    if (self.effectiveScale < 1.0) {
        self.effectiveScale = 1.0;
    }
    
    CGFloat maxScale = [[self.imageOutPut connectionWithMediaType:AVMediaTypeVideo] videoMaxScaleAndCropFactor];
    if (self.effectiveScale > maxScale) {
        self.effectiveScale = maxScale;
    }
    
    [CATransaction begin];
    [CATransaction setAnimationDuration:0.025];
//    [self.previewLayer setAffineTransform:CGAffineTransformMakeScale(self.effectiveScale, self.effectiveScale)];
    [self.videoPreviewView.layer setAffineTransform:CGAffineTransformMakeScale(self.effectiveScale, self.effectiveScale)];
    [CATransaction commit];
    
    
}

// 把当前的比例付给初始比例(不写会跳)
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    if ([gestureRecognizer isKindOfClass:[UIPinchGestureRecognizer class]]) {
        self.beginGestureScale = self.effectiveScale;
    }
    return YES;
}


// 手势更换滤镜
- (void)swipChangeFilter:(UISwipeGestureRecognizer *)swip{
    self.filterIndex--;
    if (self.filterIndex < 0) {
        self.filterIndex = self.filterArr.count - 1;
    }
    
}

















@end
